<template>
  <div style="width:100%;height:100%">
    <div class="result-header">
      {{ showType }}
    </div>
    <div class="analy-result-process-wrap">
      <div class="analy-result-process-header">分析流程</div>
    </div>
    <div class="analy-result-process-content">
      <div class="process-header">
        <el-icon class='database' :size="25">
          <Coin />
        </el-icon>
        <span style="line-height: 20px; font-weight: 700;">
          数据源
        </span>
      </div>
      <div class="process-body">
        <span class="body-1">电商企业供应商数据</span>
      </div>
    </div>
    <div class="analy-result-process-content">
      <div class="process-header">
        <el-icon class='database' :size="25">
          <HelpFilled />
        </el-icon>
        <span style="line-height: 20px; font-weight: 700;">
          算法配置
        </span>
      </div>
      <div class="process-body">
        <p class="body-p">算法：{{ showType }}</p>
        <p class="body-p">变量：变量X：｛{{ xListStr }}｝;变量Y：{信用评级} </p>
      </div>
    </div>
    <div class="analy-result-process-content">
      <div class="process-header">
        <el-icon class='database' :size="25">
          <Tickets />
        </el-icon>
        <span style="line-height: 20px; font-weight: 700;">
          分析结果
        </span>
      </div>
      <div class="process-body">
        <p class="body-p" v-if="showType !== '线性回归'">{{ showType }}基于MSE、RMSE、MAE、MAPE、R²指标对模型进行评价，请看详细结论。</p>
        <p class="body-p" v-else>线性回归用于研究自变量与因变量之间的线性关系：F检验的显著性P值为0.000***，水平上呈现显著性，拒绝回归系数为0的原假设，因此模型基本满足要求。</p>
      </div>
    </div>
    <!-- 分析步骤 -->
    <div class="analy-step">
      <div class="analy-result-process-wrap">
        <div class="analy-result-process-header">分析步骤</div>
      </div>
      <div v-if="showType == 'XGBoost回归'">
        <div class="step-text">
          1.通过训练集数据来建立XGBoost回归模型。
        </div>
        <div class="step-text">
          2.通过建立的XGBoost来计算特征重要性。
        </div>
        <div class="step-text">
          3.将建立的XGBoost回归模型应用到训练、测试数据，得到模型评估结果。
        </div>
        <div class="step-text">
          4.由于XGBoost具有随机性，每次运算的结果不一样，若保存本次训练模型，后续可以直接上传数据代入到本次训练模型进行计算预测。
        </div>
        <div class="step-text">
          5.注：XGBoost无法像传统模型一样得到确定的方程，通常通过测试数据预测精度来对模型进行评价。
        </div>
      </div>
      <div v-if="showType == '决策树回归'">
        <div class="step-text">
          1.通过训练集数据来建立决策数回归模型，得到决策树结构。
        </div>
        <div class="step-text">
          2.通过建立的决策树来计算特征重要性。
        </div>
        <div class="step-text">
          3.将建立的决策树回归模型应用到训练、测试数据，得到模型评估结果。
        </div>
        <div class="step-text">
          4.由于决策树具有随机性，每次运算的结果不一样，若保存本次训练模型，后续可以直接上传数据代入到本次训练模型进行计算预测。
        </div>
        <div class="step-text">
          5.注：决策树无法像传统模型一样得到确定的方程，通常通过测试数据预测精度来对模型进行评价。
        </div>
      </div>
      <div v-if="showType == 'K近邻（KNN）回归'">
        <div class="step-text">
          1.通过训练集数据来建立K近邻(KNN)回归模型。
        </div>
        <div class="step-text">
          2.将建立的K近邻(KNN)回归模型应用到训练、测试数据，得到模型评估结果。
        </div>
        <div class="step-text">
          3.若K近邻(KNN)选择了数据洗牌功能，每次运算的结果不一样，若保存本次训练模型，后续可以直接上传数据代入到本次训练模型进行计算预测。
        </div>
        <div class="step-text">
          4.
          注：K近邻(KNN)无法像传统模型一样得到确定的方程，通常通过测试数据预测精度来对模型进行评价。
        </div>
      </div>
      <div v-if="showType == '随机森林回归'">
        <div class="step-text">
          1.通过训练集数据来建立随机森林回归模型。</div>
        <div class="step-text">
          2.通过建立的随机森林来计算特征重要性。
        </div>
        <div class="step-text">
          3.将建立的随机森林回归模型应用到训练、测试数据，得到模型评估结果。 </div>
        <div class="step-text">
          4.由于随机森林具有随机性，每次运算的结果不一样，若保存本次训练模型，后续可以直接上传数据代入到本次训练模型进行计算预测。
        </div>
        <div class="step-text">
          5.注：随机森林无法像传统模型一样得到确定的方程，通常通过测试数据预测精度来对模型进行评价。
        </div>
      </div>
    </div>
    <div class="analy-step">
      <div class="analy-result-process-wrap">
        <div class="analy-result-process-header">详细结论</div>
      </div>
      <div>
        <div class="result-table">
          <span class="sub-title-text">
            输出结果1：模型评估结果
          </span>
          <table style="text-align: center;width:95%">
            <tr>
              <th></th>
              <th>MSE</th>
              <th>RMSE</th>
              <th>MAE</th>
              <th>MAPE</th>
              <th>R²</th>
            </tr>
            <tbody>
              <tr>
                <td>训练集</td>
                <td>{{ bpSvrDetailData.mse }}</td>
                <td>{{ bpSvrDetailData.rmse }}</td>
                <td>{{ bpSvrDetailData.mae }}</td>
                <td>{{ bpSvrDetailData.mape }}</td>
                <td>{{ bpSvrDetailData.r2 }}</td>
              </tr>
              <!-- <tr>
                <td>测试集</td>
                <td>{{ bpSvrDetailData.mse_test }}</td>
                <td>{{ bpSvrDetailData.rmse_test }}</td>
                <td>{{ bpSvrDetailData.mae_test }}</td>
                <td>{{ bpSvrDetailData.mape_test }}</td>
                <td>{{ bpSvrDetailData.r2_test }}</td>
              </tr> -->
            </tbody>
          </table>
        </div>
        <div class="step-text">
          上表中展示了交叉验证集、训练集和测试集的预测评价指标，通过量化指标来衡量bp神经网络回归的预测效果。其中，通过交叉验证集的评价指标可以不断调整超参数，以得到可靠稳定的模型。
        </div>
        <div class="step-text">
          ● MSE（均方误差）： 预测值与实际值之差平方的期望值。取值越小，模型准确度越高。
        </div>
        <div class="step-text">
          ● RMSE（均方根误差）：为MSE的平方根，取值越小，模型准确度越高。
        </div>
        <div class="step-text">
          ● MAE（平均绝对误差）： 绝对误差的平均值，能反映预测值误差的实际情况。取值越小，模型准确度越高。
        </div>
        <div class="step-text">
          ● MAPE（平均绝对百分比误差）： 是 MAE 的变形，它是一个百分比值。取值越小，模型准确度越高。
        </div>
        <div class="step-text">
          ● R²： 将预测值跟只使用均值的情况下相比，结果越靠近 1 模型准确度越高。
        </div>
        <div class="result-table">
          <span class="sub-title-text">
            输出结果2：预测结果
            <el-select v-model="tableChange" @change="hanldeChangeTable" style="margin-left: 58%;">
              <el-option label="测试集" :value="1" />
              <el-option label="训练集" :value="2" />
            </el-select>
          </span>
          <table style="text-align: center; margin-bottom: 20px; width:95%" id="myTable" v-show="tableChange == 1">
            <thead>
              <tr>
                <th>预测测试集结果Y</th>
                <th v-for="item in bpSvrDetailData.bpSvrDetailHeader">{{ item }}</th>
              </tr>
            </thead>
          </table>
          <table style="text-align: center; margin-bottom: 20px; width:99%;" id="myTable1" v-if="tableChange == 2">
            <thead>
              <tr>
                <th>预测结果集结果Y</th>
                <th v-for="item in bpSvrDetailData.bpSvrDetailHeader">{{ item }}</th>
              </tr>
            </thead>
          </table>
        </div>
      </div>

      <div class="foot-buttom">
        <div v-if="!!listComeData">
          <el-button @click="emitter.emit('closeNewApprovalResult')"> 返回 </el-button>
        </div>
        <div v-else>
          <el-button @click="saveSSS()" type="primary">保存
          </el-button>
          <el-button @click="emitter.emit('saveNewApprovalResult')" type="primary">取消并返回
          </el-button>
        </div>
      </div>
    </div>
  </div>
  <!-- 确认提交弹窗 -->
</template>
 
<script setup lang='ts'>
import { ref, watch, reactive, nextTick, onMounted } from 'vue';
import { emitter } from "@/utils/mitt";
import { useRoute } from "vue-router";
import {
  EvaluationAlgorithmResultCreate,
} from "@/api/stu/SupplyChainFinance";
import { ElMessage } from 'element-plus';
const props = defineProps({
  showType: {
    type: String,
    required: true
  },
  financingApprovalId: {
    type: String,
    required: true
  },
  acrmId: {
    type: String,
    required: true
  },
  //算法类型
  detailData: {
    type: Object,
    required: true
  },
  listComeData: {
    type: Object,
    required: true
  },
  data: {
    type: Object,
    required: true
  },
});
const route = useRoute()
const xListStr = ref()
//bp和svr详情数据（列表查看以及生成报告）
const bpSvrDetailData = reactive({
  type: '',
  mse: 0,
  rmse: 1,
  mae: 2,
  mape: 3,
  r2: 4,
  mse_test: 5,
  rmse_test: 6,
  mae_test: 7,
  mape_test: 8,
  r2_test: 9,
  bpSvrDetailHeader: [],
  y_pred_train: [], //预测训练集数据
  y_pred_test: [],//预测测试集数据
})
const lineDetaliData = reactive({
  type: '',
  xListStr: [],
  dataList: [],
  r2: '',
  adjustr2: '',
  f: ''
})
const tableChange = ref(1)

onMounted(() => {
  //如果是详情直接跳到查看结果
  if (!!props.listComeData) {
    handleJumpDetail()
  } else {
    handleNewReport()
  }
})
function handleJumpDetail() {
  if (props.listComeData.bpSvrDetailHeader) {
    xListStr.value = props.listComeData.bpSvrDetailHeader.join(',')
    nextTick(() => {
      bpSvrDetailData.bpSvrDetailHeader = props.listComeData.bpSvrDetailHeader
      bpSvrDetailData.mse = props.listComeData.mse
      bpSvrDetailData.rmse = props.listComeData.rmse
      bpSvrDetailData.mae = props.listComeData.mae
      bpSvrDetailData.mape = props.listComeData.mape
      bpSvrDetailData.r2 = props.listComeData.r2
      bpSvrDetailData.mse_test = props.listComeData.mse_test
      bpSvrDetailData.rmse_test = props.listComeData.rmse_test
      bpSvrDetailData.mae_test = props.listComeData.mae_test
      bpSvrDetailData.mape_test = props.listComeData.mape_test
      bpSvrDetailData.r2_test = props.listComeData.r2_test
      bpSvrDetailData.y_pred_test = props.listComeData.y_pred_test;
      bpSvrDetailData.y_pred_train = props.listComeData.y_pred_train;
      //生成Table 
      if (bpSvrDetailData.y_pred_test.length > 0) {
        const table = document.getElementById("myTable");
        tableChange.value = 1
        nextTick(() => {
          for (var i = 0; i < bpSvrDetailData.y_pred_test.length; i++) {
            var row = table.insertRow(i + 1);
            for (var j = 0; j < bpSvrDetailData.y_pred_test[i].length; j++) {
              var cell = row.insertCell(j);
              cell.innerHTML = bpSvrDetailData.y_pred_test[i][j];
              cell.style.border = '1px solid #bab9b9';
            }
          }
        })
      } else {
        tableChange.value = 2
        nextTick(() => {
          const table = document.getElementById("myTable1");
          console.log(bpSvrDetailData.y_pred_train.length)
          for (var i = 0; i < bpSvrDetailData.y_pred_train.length; i++) {
            var row = table.insertRow(i + 1);
            for (var j = 0; j < bpSvrDetailData.y_pred_train[i].length; j++) {
              var cell = row.insertCell(j);
              cell.innerHTML = bpSvrDetailData.y_pred_train[i][j];
              cell.style.border = '1px solid #bab9b9';
            }
          }
        })
      }

    })
  } else {
    xListStr.value = props.listComeData.xListStr.join(',')
    lineDetaliData.dataList = props.listComeData.dataList
    lineDetaliData.r2 = props.listComeData.r2
    lineDetaliData.adjustr2 = props.listComeData.adjustr2
    lineDetaliData.f = props.listComeData.f
  }
}
function handleNewReport() {
  const { data, showType, detailData } = props;
  var arr = data.indexSelection.map(item => item.Key);
  xListStr.value = data.indexSelection.map(item => item.Value).join(',');
  nextTick(() => {
    bpSvrDetailData.type = showType
    bpSvrDetailData.bpSvrDetailHeader = data.indexSelection.map(item => item.Value)
    const head = arr
    const result = []; //测试集
    const result1 = [];//训练集
    bpSvrDetailData.mse = detailData.mse
    bpSvrDetailData.rmse = detailData.rmse
    bpSvrDetailData.mae = detailData.mae
    bpSvrDetailData.mape = detailData.mape
    bpSvrDetailData.r2 = detailData.r2
    bpSvrDetailData.mse_test = detailData.mse_test
    bpSvrDetailData.rmse_test = detailData.rmse_test
    bpSvrDetailData.mae_test = detailData.mae_test
    bpSvrDetailData.mape_test = detailData.mape_test
    bpSvrDetailData.r2_test = detailData.r2_test
    //处理测试集数据
    for (const obj of detailData.test_quotaAssessment_data) {
      const item = [];
      for (const property of head) {
        item.push(obj[property]);
      }
      result.push(item);
    }
    for (let i = 0; i < result.length; i++) {
      result[i].unshift(detailData.y_pred_test[i] || detailData.y_pred_train[i]);
    }
    //处理训练集数据
    for (const obj of detailData.quotaAssessment_data) {
      const item = [];
      for (const property of head) {
        item.push(obj[property]);
      }
      result1.push(item);
    }
    for (let i = 0; i < result1.length; i++) {
      result1[i].unshift(detailData.y_pred_test[i] || detailData.y_pred_train[i]);
    }
    bpSvrDetailData.y_pred_test = result;
    bpSvrDetailData.y_pred_train = result1;
    //生成Table 
    console.log(bpSvrDetailData.y_pred_test);
    console.log(bpSvrDetailData.y_pred_train);
    if (bpSvrDetailData.y_pred_test.length > 0) {
      const table = document.getElementById("myTable");
      tableChange.value = 1
      nextTick(() => {
        for (var i = 0; i < bpSvrDetailData.y_pred_test.length; i++) {
          var row = table.insertRow(i + 1);
          for (var j = 0; j < bpSvrDetailData.y_pred_test[i].length; j++) {
            var cell = row.insertCell(j);
            cell.innerHTML = bpSvrDetailData.y_pred_test[i][j];
            cell.style.border = '1px solid #bab9b9';
          }
        }
      })
    } else {
      tableChange.value = 2
      nextTick(() => {
        const table = document.getElementById("myTable1");
        console.log(bpSvrDetailData.y_pred_train.length)
        for (var i = 0; i < bpSvrDetailData.y_pred_train.length; i++) {
          var row = table.insertRow(i + 1);
          for (var j = 0; j < bpSvrDetailData.y_pred_train[i].length; j++) {
            var cell = row.insertCell(j);
            cell.innerHTML = bpSvrDetailData.y_pred_train[i][j];
            cell.style.border = '1px solid #bab9b9';
          }
        }
      })
    }
  })
}

function hanldeChangeTable() {
  if (tableChange.value == 1) {
    return
  } else {
    nextTick(() => {
      var table = document.getElementById("myTable1");
      console.log(bpSvrDetailData.y_pred_train.length)
      for (var i = 0; i < bpSvrDetailData.y_pred_train.length; i++) {
        var row = table.insertRow(i + 1);
        for (var j = 0; j < bpSvrDetailData.y_pred_train[i].length; j++) {
          var cell = row.insertCell(j);
          cell.innerHTML = bpSvrDetailData.y_pred_train[i][j];
          cell.style.border = '1px solid #bab9b9';
        }
      }
    })
  }
}

async function saveSSS() {
  const { showType } = props;
  const data = {
    taskId: route.query.taskId,
    planId: route.query.planId,
    financingApprovalId: props.financingApprovalId,
    algorithmResultId: props.acrmId,
    type: 2,
    algorithmCalculateResult: JSON.stringify(bpSvrDetailData),
  }
  let res = await EvaluationAlgorithmResultCreate(data)
  if (res.success) {
    ElMessage.success('额度核定成功！')
    emitter.emit('closeNewApprovalResult')
  } else {
    ElMessage.error(res.msg)
  }
}

</script>
<style>
.box-item-draggle {
  max-width: 50%;
}
</style>
<style scoped lang="scss" >
.container {
  height: 100%;
  display: flex;
}

.left-panel {
  width: 200px;
  border-right: 1px solid #eef1f5;
  user-select: none;
}

.flexible-panel {
  flex-grow: 1;
  overflow-y: auto;
  overflow-x: hidden;
  flex: 1;
}

.list_item {
  padding: 0 12px 0 20px;
  font-size: 12px;
  cursor: move;
  color: #6a6f77;
  align-items: center;
  margin-bottom: 12px;
}

.top-title {
  padding: 10px 12px 10px 20px;
  margin-bottom: 15px;
  border-bottom: 1px solid #eef1f5;
  display: flex;
  justify-content: space-between
}

.var-des {
  padding: 18px 20px;
  font-size: 12px;
}

.drag-area {
  margin-left: 20px;
  border: 1px dashed #d8d8d8;
  overflow-y: auto;
  min-height: 40px;
  flex-basis: 40px;
  height: 40px;
  flex-grow: 0;
}

.drag-areax {
  margin-left: 20px;
  border: 1px dashed #d8d8d8;
  overflow-y: auto;
  min-height: 240px;
  flex-basis: 40px;
  height: 40px;
  flex-grow: 0;
}

.drag-box {
  width: 100%;
  height: 100%;
  position: relative;
}

.yStyle {
  height: 100%;
  width: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  color: #aaadb1;
  font-size: 14px;
  position: absolute;
  left: 0;
  top: 0;
}

.list-item {
  height: 30px;
  font-size: 12px;
  padding: 0 20px;
  align-items: center;
  cursor: move;
  justify-content: space-between;
  display: flex;
  user-select: none;
}

.close-icon {
  position: relative;
  display: inline-block;
  width: 20px;
  height: 20px;
  cursor: pointer;
}

.close-icon::before,
.close-icon::after {
  content: "";
  position: absolute;
  top: 50%;
  left: 50%;
  width: 2px;
  height: 10px;
  background-color: red;
  transform: translate(-50%, -50%) rotate(45deg);
}

.close-icon::before {
  transform: translate(-50%, -50%) rotate(-45deg);
}

.condition {
  margin-top: 15px;
  margin-left: 20px;
  display: flex;
}

.paramsBottom {
  display: flex;
  align-items: center;
  font-size: 12px;
}

.detail {
  color: #1a78ff;
  cursor: pointer;
  font-size: 12px;
  display: inline-flex;
  flex-wrap: nowrap;
}

.setting-item {
  display: flex;
  align-items: center;
  margin-top: 10px;
}

.foot-buttom {
  display: flex;
  text-align: right;
  justify-content: center;
  margin-top: 50px;
}

.result-header {
  padding: 0px 30px px;
  height: 40px;
  width: 100%;
  line-height: 40px;
  font-family: PingFangSC, PingFangSC-Medium;
  text-align: left;
  color: #2b323d;
  border-bottom: 1px solid #eef1f5;
}

.analy-result-process-wrap {
  margin-top: 16px;
  margin-bottom: 20px;
  font-family: PingFangSC, PingFangSC-Medium;
}

.analy-result-process-header {
  color: rgb(43, 50, 61);
  height: 22px;
  margin-bottom: 16px;
  font-weight: 700;
  display: flex;
  font-size: 14px;
  align-items: center;
}

.analy-result-process-header::before {
  content: "";
  width: 4px;
  height: 16px;
  margin-right: 10px;
  background-color: rgb(26, 120, 255);
}

.analy-result-process-content {
  margin-left: 14px;
}

.process-header {
  display: flex;
  font-size: 14px;
  align-items: center;
  color: rgb(43, 50, 61);
  margin: 10px 0px 8px;
}

.database {
  color: rgb(26, 120, 255);
  margin-right: 8px
}

.process-body {
  margin-left: 14px;
  padding-left: 22px;
  border-left: 1px solid rgba(26, 120, 255, 0.3);
  min-height: 28px;
  line-height: 12px;
  position: relative;
  font-weight: 400;
  font-size: 12px;
}

.process-body::before {
  content: "";
  width: 0px;
  height: 0px;
  border-width: 4px;
  border-style: solid;
  border-image: initial;
  border-color: rgba(26, 120, 255, 0.5) transparent transparent;
  position: absolute;
  left: -4px;
  bottom: -8px;
  translate: -0.5px;
}

.body-1 {
  text-decoration: underline;
  color: rgb(26, 120, 255);
  line-height: 18px;
  cursor: pointer;
}

.body-p {
  color: rgb(106, 111, 119);
  line-height: 18px;
  margin-bottom: 4px;
  width: 100%;
}


table,
th,
td {
  border: 1px solid #bab9b9;
  border-collapse: collapse;
}

.analy-step {
  margin-bottom: 40px;
  margin-top: 16px;
  font-size: 14px;
}

.step-text {
  margin-left: 14px;
  font-family: PingFangSC, PingFangSC-Regular;
  font-weight: 400;
  color: #6a6f77;
  white-space: pre-wrap;
}

.result-table {
  margin-bottom: 20px;
  margin-left: 20px
}

.sub-title-text {
  font-family: PingFangSC, PingFangSC-Medium;
  font-weight: 700;
  color: #2b323d;
  height: 26px;
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}

.wide-cell {
  width: 50px;
  /* 自定义宽度，可以根据需要进行调整 */
}
</style>
